package com.woniu.consumer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.woniu.client.OrderClient;
import com.woniu.client.ProductClient;
import com.woniu.commons.model.Result;
import com.woniu.commons.model.StateData;
import com.woniu.model.YGoods;
import com.woniu.model.YGoodsDto;
import com.woniu.model.model.YGoodsItem;
import com.woniu.model.model.YGoodsOrder;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@Component
@RabbitListener(queues = "ordernum_queue")
public class OrderNumQueueConsumer {

    @Resource
    private AlipayClient alipayClient;
    @Resource
    private ProductClient productClient;
    @Resource
    private OrderClient orderClient;



    @RabbitHandler
    @GlobalTransactional(rollbackFor = Throwable.class)
    public void checkOrder(String orderNum) throws AlipayApiException {
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        //请二选一设置
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderNum + "\"}");
        //请求
        String result = alipayClient.execute(alipayRequest).getBody();

        String response = JSONUtil.parseObj(result).get("alipay_trade_query_response").toString();
        String payCode=JSONUtil.parseObj(response).get("code").toString();
        if ("10000".equals(payCode)) {
            //已经给钱了，但是订单未支付
            String status = JSONUtil.parseObj(response).get("trade_status").toString();
            String payTime = JSONUtil.parseObj(response).get("send_pay_date").toString();
            if ("TRADE_SUCCESS".equals(status)){

                Result<YGoodsOrder> yGoodsOrder = orderClient.byId(orderNum);
                YGoodsOrder orderInfo = yGoodsOrder.getData();
                if (Objects.equals(orderInfo.getOrderState(), StateData.GOODS_ORDER_STATE_DISABLED)) {
                    //如果订单状态不是未支付才进下一步操作
                    orderInfo.setOrderState(StateData.GOODS_ORDER_STATE_START);
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime parse = LocalDateTime.parse(payTime, formatter);
                    orderInfo.setPayTime(parse);

                    //修改冻结量

                    Result<List<YGoodsItem>> listResult = orderClient.listByClassType(orderNum);
                    List<YGoodsItem> goodsItems = listResult.getData();

                    for (YGoodsItem item :goodsItems){
                        Result<YGoodsDto> yGoodsDtoResult = productClient.byId(item.getGoodsId());
                        YGoodsDto data = yGoodsDtoResult.getData();
                        YGoods yGoods = BeanUtil.toBean(data, YGoods.class);
                        yGoods.setGoodsFrooze(yGoods.getGoodsFrooze() - item.getGoodsNum());
                        productClient.updateByIdGoods(yGoods);
                    }
                    orderClient.updateByIdGoodsOrder(orderInfo);
                }
            }
        }else {
            //用户为订单进行支付
            //取消订单，还原库存
            Result<YGoodsOrder> yGoodsOrderResult = orderClient.byId(orderNum);
            YGoodsOrder goodsOrder = yGoodsOrderResult.getData();
            goodsOrder.setOrderState(StateData.GOODS_ORDER_STATE_FULL);
            orderClient.updateByIdGoodsOrder(goodsOrder);

            Result<List<YGoodsItem>> listResult = orderClient.listByClassType(orderNum);
            List<YGoodsItem> goodsItems = listResult.getData();
            for (YGoodsItem item:goodsItems){
                Result<YGoodsDto> yGoodsDtoResult = productClient.byId(item.getGoodsId());
                YGoodsDto data = yGoodsDtoResult.getData();
                YGoods yGoods = BeanUtil.toBean(data, YGoods.class);
                yGoods.setGoodsNum(yGoods.getGoodsNum() + item.getGoodsNum());
                yGoods.setGoodsFrooze(yGoods.getGoodsFrooze() - item.getGoodsNum());
                productClient.updateByIdGoods(yGoods);
            }
        }
    }








}
